const app = getApp();
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value: "",
    orderList: [],
    total:0,
    condition:{}
  }, 
  // 获取集合记录总数
  async getTotal(){
    const countResult = await db.collection("orderList").where(this.data.condition).orderBy('createTime',"desc").count();
    const total = countResult.total;
    this.setData({
      total:total
    })
  },
  getData() {
    wx.showLoading({
      title: '正在加载',
    })
    db.collection("orderList").skip(this.data.orderList.length).limit(20).where(this.data.condition).orderBy('createTime',"desc").get().then(res=>{
      this.setData({
        orderList:this.data.orderList.concat(res.data)
      })
      wx.hideLoading();
    })
  },
  async search(e) {
    let num = e.type == 'confirm' ? e.detail.value : e.detail.value.num;
    let condition = {
      num: db.RegExp({
        regexp: '.*' + num,
        options: 'i',
      })
    }
    if (num == '') {
      this.setData({
        orderList:[],
        condition:{}
      })
      await this.getTotal();
      this.getData();
    } else {
      this.setData({
        orderList:[],
        condition:condition
      })
      await this.getTotal();
      this.getData()
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:  function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow:async function () {
    if (Object.keys(this.data.condition).length==0) {
      await this.getTotal();
      this.setData({
        orderList:[],
      })
      this.getData();
    }else{
      await this.getTotal();
      this.setData({
        orderList:[],
      })
      this.getData();
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.orderList.length < this.data.total) {
      this.getData();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})